package com.codemes.happylist.modules.pdf.service;


import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.util.Map;

/**
 * html 模板转pdf 利用 wkhtmltopdf.exe
 *
 * @author lvqiansheng
 */
@Slf4j
public class WhHtmlToPdf {

    /**
     * wkhtmltopdf在系统中的路径
     */
    private static String toPdfTool = "/usr/bin/wkhtmltopdf";
    /**
     * html转pdf
     *
     * @param htmlPath  html路径，可以是硬盘上的路径，也可以是网络路径
     * @param destPath pdf保存路径
     * @return 转换成功返回 pdf 路径
     */
    public static String convert(String htmlPath, String destPath) throws Exception{
        log.info("pdfPath:{}",destPath);
        File file = new File(destPath);
        File parent = file.getParentFile();
        //如果pdf保存路径不存在，则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }
        log.info("fileName:{}",htmlPath);
        StringBuilder cmd = new StringBuilder();
        if (System.getProperty("os.name").indexOf("Windows") == -1) {
            //非windows 系统
            toPdfTool = "/usr/bin/wkhtmltopdf";
        }
        cmd.append(toPdfTool);
        cmd.append(" ");
        cmd.append(htmlPath);
        cmd.append(" ");
        cmd.append(destPath);
        try {
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            proc.waitFor();
        } catch (InterruptedException e) {
            log.error("生成操作证pdf异常:",e);
            e.printStackTrace();
            Thread.currentThread().interrupt();
        } catch (Exception e) {
            log.error("生成操作证pdf异常:",e);
            e.printStackTrace();
        }
        //delete(fileName);
        log.info("destPath:{}",destPath);
        return destPath;
    }

    /**
     * 测试方法
     * @param fileName
     * @return
     */
    public static String readFileContent(String fileName) {
        File file = new File(fileName);
        log.info("file2:{}",file.exists());
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        log.info("htmlData:{}",sbf.toString());
        return sbf.toString();
    }
}
